package com.ffcc.fitness.card.service.impl;

import com.ffcc.fitness.card.mapper.CardMapper;
import com.ffcc.fitness.card.pojo.dto.CardInsertParam;
import com.ffcc.fitness.card.pojo.dto.CardUpdateParam;
import com.ffcc.fitness.card.pojo.entity.Card;
import com.ffcc.fitness.card.pojo.vo.CardVO;
import com.ffcc.fitness.card.pojo.vo.CommentVO;
import com.ffcc.fitness.card.service.CardService;
import com.ffcc.fitness.comment.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CardServiceImpl implements CardService {
    
    @Autowired
    private CardMapper cardMapper;
    
    @Autowired
    private CommentService commentService;

    @Override
    public List<CardVO> selectAllCards() {
        // 查询所有器械卡片基本信息
        List<CardVO> cardVOList = cardMapper.selectAllCards();
        log.info("查出来的器械卡片信息：" + cardVOList);

        // 为每个卡片查询点赞数、评论数和评论内容
        populateCardDetails(cardVOList);

        return cardVOList;
    }
    @Override
    public List<CardVO> selectCardsByCoachId(Long coachId) {
        // 查询指定教练发布的器械卡片基本信息
        List<CardVO> cardVOList = cardMapper.selectCardsByCoachId(coachId);
        log.info("查询教练{}发布的器械卡片信息：{}", coachId, cardVOList);

        // 为每个卡片查询点赞数、评论数和评论内容
        populateCardDetails(cardVOList);

        return cardVOList;
    }
      /**
     * 为卡片列表填充详细信息（点赞数、评论数、评论内容）
     * 使用简化评论系统
     */
    private void populateCardDetails(List<CardVO> cardVOList) {
        for (CardVO cardVO : cardVOList) {
            Long cardId = cardVO.getCardId();

            // 查询点赞数
            Long likeCount = cardMapper.getLikeCount(cardId);
            cardVO.setLikeCount(likeCount);

            // 使用新的评论服务查询评论数量
            // targetType = 1 表示器械卡片
            Long commentCount = commentService.getCommentCount(cardId, 1);
            cardVO.setCommentCount(commentCount);

            // 查询评论内容并转换为JSON字符串
            List<CommentVO> commentVOList = commentService.getCommentsByTarget(cardId, 1);
            if (commentVOList != null && !commentVOList.isEmpty()) {
                StringBuilder contentBuilder = new StringBuilder();
                for (CommentVO comment : commentVOList) {
                    contentBuilder.append("{\"commentId\":").append(comment.getCommentId())
                            .append(",\"content\":\"").append(comment.getContent())
                            .append("\",\"nickname\":\"").append(comment.getNickname())
                            .append("\",\"createTime\":\"").append(comment.getCreateTime())
                            .append("\"},");
                }
                // 移除最后的逗号
                if (contentBuilder.length() > 0) {
                    contentBuilder.setLength(contentBuilder.length() - 1);
                }
                cardVO.setContent("[" + contentBuilder.toString() + "]");
            } else {
                cardVO.setContent("[]");
            }
        }
    }

    @Override
    public void insert(CardInsertParam cardInsertParam) {
        Card card = new Card();
        BeanUtils.copyProperties(cardInsertParam, card);
        card.setCreateTime(LocalDateTime.now());
        card.setUpdateTime(LocalDateTime.now());
        cardMapper.insert(card);
    }
    
    @Override
    public void update(CardUpdateParam cardUpdateParam) {
        Card card = new Card();
        BeanUtils.copyProperties(cardUpdateParam, card);
        card.setUpdateTime(LocalDateTime.now());
        int result = cardMapper.update(card);
        if (result == 0) {
            log.warn("更新器械卡片失败，卡片不存在或无权限，cardId: {}", cardUpdateParam.getCardId());
            throw new RuntimeException("更新失败，器械卡片不存在或无权限修改");
        }
        log.info("成功更新器械卡片，cardId: {}", cardUpdateParam.getCardId());
    }

    @Override
    public void delete(Long cardId) {
        int result = cardMapper.delete(cardId);
        if (result == 0) {
            log.warn("删除器械卡片失败，卡片不存在或已被删除，cardId: {}", cardId);
            throw new RuntimeException("删除失败，器械卡片不存在");
        }
        log.info("成功删除器械卡片，cardId: {}", cardId);
    }
}